package com.seari.web.controller;

import java.text.DecimalFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.seari.Utils.HandlerNullUtils;
import com.seari.Utils.StringUtils;
import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.commonutils.redis.ex.JedisNotInitializeException;
import com.seari.main.StartUpClass;
import com.seari.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.seari.pojo.MessageBean;
import redis.clients.jedis.Jedis;

@Controller
public class DeviceController {

	@Autowired
	private DeviceService deviceService;

	@RequestMapping("device")
	public String index() {
		return "device";
	}

	/**
	 * 设备监视
	 * 
	 * @return
	 */
	@RequestMapping("device/getFaultMonitoringData")
	@ResponseBody
	public MessageBean getFaultMonitoringData() {
		MessageBean messageBean = new MessageBean();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> faultMonitoringData = new HashMap<String, Object>();
		try {
			if ("test".equals(StartUpClass.faultMonitoringData)) {
				faultMonitoringData.put("fas", "自动");
				faultMonitoringData.put("emcs", "运行故障");
				faultMonitoringData.put("psdUp", "开");
				faultMonitoringData.put("psdDpwn", "开");
				faultMonitoringData.put("afc", "正常模式");
				faultMonitoringData.put("acs", "正常");
				faultMonitoringData.put("pis", "正常");
				faultMonitoringData.put("pa", "正常");
				faultMonitoringData.put("cctv", "正常");
			} else {
				Jedis jedis = null;
				try {
					jedis = JedisUtilProxy.getJedis();
				} catch (JedisNotInitializeException e) {
					e.printStackTrace();
				}
				// fas模式
				String fas = jedis.hmget("17DATA", "3145").get(0);
				if ("0".equals(fas)) {
					faultMonitoringData.put("fas", "自动");
				} else if ("1".equals(fas)) {
					faultMonitoringData.put("fas", "手动");
				}
				// emcs模式
				int emcs = Integer.parseInt(jedis.hmget("17DATA", "11").get(0));
				if (emcs >= 1 && emcs <= 6) {
					faultMonitoringData.put("emcs", "正常运行");
				} else if (emcs >= 7 && emcs <= 8) {
					faultMonitoringData.put("emcs", "停运");
				} else if (emcs == 0 || emcs > 8) {
					faultMonitoringData.put("emcs", "模式故障");
				}
				// psd 上行 0 关 1开
				int psdUp = Integer.parseInt(jedis.hmget("OTHER_DATA", "25")
						.get(0));
				if (psdUp == 0) {
					faultMonitoringData.put("psdUp", "关");
				} else if (psdUp == 1) {
					faultMonitoringData.put("psdUp", "开");
				}
				// psd 下行0 关 1开
				int psdDpwn = Integer.parseInt(jedis.hmget("OTHER_DATA", "26")
						.get(0));
				if (psdDpwn == 0) {
					faultMonitoringData.put("psdDpwn", "关");
				} else if (psdDpwn == 1) {
					faultMonitoringData.put("psdDpwn", "开");
				}
				// afc 先判断22609(7112)，为1运营结束，为0再判断其他
				List<String> afc = jedis.hmget("17DATA", "7106", "7107",
						"7108", "7110", "7112", "7119");
				if ("0".equals(afc.get(5))) {
					if ("1".equals(afc.get(0)) && "0".equals(afc.get(1))
							&& "0".equals(afc.get(2)) && "0".equals(afc.get(3))
							&& "0".equals(afc.get(5))) {
						faultMonitoringData.put("afc", "时间免检");
					} else if ("0".equals(afc.get(0)) && "1".equals(afc.get(1))
							&& "0".equals(afc.get(2)) && "0".equals(afc.get(3))
							&& "0".equals(afc.get(5))) {
						faultMonitoringData.put("afc", "日期免检");
					} else if ("0".equals(afc.get(0)) && "0".equals(afc.get(1))
							&& "1".equals(afc.get(2)) && "0".equals(afc.get(3))
							&& "0".equals(afc.get(5))) {
						faultMonitoringData.put("afc", "进/出站免检");
					} else if ("0".equals(afc.get(0)) && "0".equals(afc.get(1))
							&& "0".equals(afc.get(2)) && "1".equals(afc.get(3))
							&& "0".equals(afc.get(5))) {
						faultMonitoringData.put("afc", "车费免检");
					} else if ("0".equals(afc.get(0)) && "0".equals(afc.get(1))
							&& "0".equals(afc.get(2)) && "0".equals(afc.get(3))
							&& "1".equals(afc.get(5))) {
						faultMonitoringData.put("afc", "紧急模式");
					} else if ("0".equals(afc.get(0)) && "0".equals(afc.get(1))
							&& "0".equals(afc.get(2)) && "0".equals(afc.get(3))
							&& "0".equals(afc.get(5))) {
						faultMonitoringData.put("afc", "正常运营");
					}
				}
				if ("1".equals(afc.get(4))) {
					faultMonitoringData.put("afc", "运营结束");
				}
				// ACS 4个点全为0为正常
				List<String> acs = jedis.hmget("17DATA", "7974", "7975",
						"7976", "7977");
				if (StringUtils.deviceStatus0(acs)) {
					faultMonitoringData.put("acs", "正常");
				} else {
					faultMonitoringData.put("acs", "故障");
				}
				// 其他
				List<String> PIS = jedis.hmget("17DATA", "8475");
				if (StringUtils.deviceStatus1(PIS)) {
					faultMonitoringData.put("pis", "正常");
				} else {
					faultMonitoringData.put("pis", "故障");
				}
				List<String> PA = jedis.hmget("17DATA", "8480");
				if (StringUtils.deviceStatus0(PA)) {
					faultMonitoringData.put("pa", "正常");
				} else {
					faultMonitoringData.put("pa", "故障");
				}
				List<String> CCTV = jedis.hmget("17DATA", "9188");
				if (StringUtils.deviceStatus0(CCTV)) {
					faultMonitoringData.put("cctv", "正常");
				} else {
					faultMonitoringData.put("cctv", "故障");
				}
				JedisUtilProxy.close(jedis);
			}
			dataMap.put("faultMonitoringData", faultMonitoringData);
			messageBean.setType("success");
			messageBean.setMessage("故障监视数据获取成功");
			messageBean.setData(dataMap);
		} catch (Exception e) {
			e.printStackTrace();
			messageBean.setType("fail");
			messageBean.setMessage("故障监视数据获取失败");
		}
		return messageBean;
	}

	/**
	 * 报障统计
	 * 
	 * @return
	 */
	@RequestMapping("device/getFaultStatisticsData")
	@ResponseBody
	public MessageBean getFaultStatisticsData() {
		MessageBean messageBean = new MessageBean();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> faultStatisticsData = new LinkedHashMap<String, Object>();
		try {
			if ("test".equals(StartUpClass.faultStatisticsData)) {
				String[] xData = { "测试服务 ", "房建装饰 ", "自动扶梯", "区间照明 ", "FAS系统" };
				int[] yData = { 11, 5, 2, 2, 1 };
				faultStatisticsData.put("xData", xData);
				faultStatisticsData.put("yData", yData);
			} else {
				Jedis jedis = null;
				try {
					jedis = JedisUtilProxy.getJedis();
				} catch (JedisNotInitializeException e) {
					e.printStackTrace();
				}
				String faultStatisStr = jedis.hget("YD_GZTJ", "fs");
				JedisUtilProxy.close(jedis);
				Map<String, Object> resultMap = JSON.parseObject(
						faultStatisStr, Map.class);
				if (!HandlerNullUtils.objectIsNull(resultMap)) {
					faultStatisticsData.put("xData", resultMap.get("xData"));
					faultStatisticsData.put("yData", resultMap.get("yData"));
				}
			}
			dataMap.put("faultStatisticsData", faultStatisticsData);
			messageBean.setType("success");
			messageBean.setMessage("故障统计数据获取成功");
			messageBean.setData(dataMap);
		} catch (Exception e) {
			e.printStackTrace();
			messageBean.setType("fail");
			messageBean.setMessage("故障统计数据获取失败");
		}
		return messageBean;
	}

	/**
	 * 报障趋势
	 * 
	 * @return
	 */
	@RequestMapping("device/getFaultTrendData")
	@ResponseBody
	public MessageBean getFaultTrendData() {
		MessageBean messageBean = new MessageBean();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> faultTrendData = new HashMap<String, Object>();
		List<Integer> thisYear = new ArrayList<Integer>();
		List<Integer> lastYear = new ArrayList<Integer>();
		try {
			if ("test".equals(StartUpClass.faultTrendData)) {
				int[] faultTrendThisYear = { 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0 };
				int[] faultTrendLastYear = { 53, 44, 24, 21, 30, 31, 24, 29,
						21, 14, 16, 48 };
				faultTrendData.put("faultTrendThisYear", faultTrendThisYear);
				faultTrendData.put("faultTrendLastYear", faultTrendLastYear);
			} else {
				Map<String, Integer> faultTrendThisYear = deviceService
						.selectFaultTrendThisYear();
				Map<String, Integer> faultTrendLastYear = deviceService
						.selectFaultTrendLastYear();

				if (!HandlerNullUtils.objectIsNull(faultTrendThisYear)) {

					thisYear = getNumList(faultTrendThisYear);
				}
				if (!HandlerNullUtils.objectIsNull(faultTrendLastYear)) {
					lastYear = getNumList(faultTrendLastYear);
				}
				faultTrendData.put("faultTrendThisYear", thisYear);
				faultTrendData.put("faultTrendLastYear", lastYear);
			}
			dataMap.put("faultTrendData", faultTrendData);
			messageBean.setType("success");
			messageBean.setMessage("故障趋势数据获取成功");
			messageBean.setData(dataMap);
		} catch (Exception e) {
			e.printStackTrace();
			messageBean.setType("fail");
			messageBean.setMessage("故障趋势数据获取失败");
		}
		return messageBean;
	}

	/**
	 * 水耗监测
	 * 
	 * @return
	 */
	@RequestMapping("device/getWaterMonitorData")
	@ResponseBody
	public MessageBean getWaterMonitorData() {
		MessageBean messageBean = new MessageBean();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			if ("test".equals(StartUpClass.WaterMonitorData)) {
				String waterAll = "110 m³";// 年度总用水
				int waterLastYear = 15;// 用水与去年同期相比
				int waterLastMonth = 3;// 用水与上月同期相比
				int waterLastDays = 3;// 昨日用水情况
				dataMap.put("waterAll", waterAll);
				dataMap.put("waterLastYear", waterLastYear);
				dataMap.put("waterLastMonth", waterLastMonth);
				dataMap.put("waterLastDays", waterLastDays);
			} else {
				Calendar cale = Calendar.getInstance();
				int month = cale.get(Calendar.MONTH);
				int day = cale.get(Calendar.DATE);
				cale.set(Calendar.DATE, 1);// 把日期设置为当月第一天
				cale.roll(Calendar.DATE, -1);// 日期回滚一天，也就是最后一天
				int maxDate = cale.get(Calendar.DATE);// 本月天数
				Properties config = StartUpClass.config;
				String[] degreePerMonth = config.getProperty("degreePerMonth")
						.split("\\|");
				int[] baseDegree = StringUtils.StringToInt(config.getProperty(
						"baseDegree").split("\\|"));
				int[] rewardDegree = StringUtils.StringToInt(config
						.getProperty("rewardDegree").split("\\|"));
				int waterAll = deviceService.getWaterAll();// 年度总用水
				int waterThisMonth = deviceService.getWaterThisMonth();// 本月用水
				int waterLastYear;// 用水与去年同期相比
				int waterLastMonth;// 用水与上月同期相比
				int waterLastDays;// 昨日用水情况
				Map<String, Integer> energyTrendThisYear = deviceService
						.getEnergyTrendDataThisYear();

				// 计算今年全年总用电。本月为止前无数据的月份用配置文件假数据替换
				if (!HandlerNullUtils.objectIsNull(energyTrendThisYear)) {
					int[] degreeThisYear = new int[12];
					for (int i = 0; i < energyTrendThisYear.size(); i++) {
						// BigDecimal 转 Integer
						Object object = energyTrendThisYear.get(String
								.valueOf(i + 1));
						degreeThisYear[i] = Integer.parseInt(String
								.valueOf(object));
						if (degreeThisYear[i] == 0 && i <= month) {
							degreeThisYear[i] = (baseDegree[i] + rewardDegree[i]) / 2;
						}
					}

				}

				if (deviceService.getWaterAllLastYear() != null) {
					float num = (float) (waterAll - deviceService
							.getWaterAllLastYear())
							/ deviceService.getWaterAllLastYear();
					DecimalFormat df = new DecimalFormat("0");// 格式化
					waterLastYear = Integer.parseInt(df.format(num * 100));
				} else {
					waterLastYear = 13;// 用水与去年同期相比
				}
				if (deviceService.getWaterLastMonth() != null) {
					float num = (float) (waterThisMonth - deviceService
							.getWaterLastMonth())
							/ deviceService.getWaterLastMonth();
					DecimalFormat df = new DecimalFormat("0");// 格式化
					waterLastMonth = Integer.parseInt(df.format(num * 100));
				} else {
					waterLastMonth = 1;// 用水与上月同期相比
				}
				String[] baseWaterMonth = config.getProperty("baseWater")
						.split("\\|");// 各月用水基准
				int baseWater = Math.round(Integer
						.parseInt(baseWaterMonth[month]) / maxDate);// 日用水=月用水/月天数
																	// 四舍五入
				float num = (float) (deviceService.getWaterLastDay() - baseWater)
						/ baseWater;
				DecimalFormat df = new DecimalFormat("0");// 格式化
				waterLastDays = Integer.parseInt(df.format(num * 100));

				dataMap.put("waterAll", waterAll + " m³");
				dataMap.put("waterLastYear", waterLastYear);
				dataMap.put("waterLastMonth", waterLastMonth);
				dataMap.put("waterLastDays", waterLastDays);
			}
			messageBean.setType("success");
			messageBean.setMessage("故障趋势数据获取成功");
			messageBean.setData(dataMap);
		} catch (Exception e) {
			e.printStackTrace();
			messageBean.setType("fail");
			messageBean.setMessage("故障趋势数据获取失败");
		}
		return messageBean;
	}

	/**
	 * 能耗监测
	 * 
	 * @return
	 */
	@RequestMapping("device/getEnergyMonitorData")
	@ResponseBody
	public MessageBean getEnergyMonitorData() {
		MessageBean messageBean = new MessageBean();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			if ("test".equals(StartUpClass.EnergyMonitorData)) {
				String eleAll = "110 kW·h";// 年度总用电
				int eleLastYear = 10;// 用电与去年同期相比
				int eleLastMonth = 8;// 用电与上月同期相比
				// String waterAll = "110 m³";// 年度总用水
				// int waterLastYear = 15;// 用水与去年同期相比
				// int waterLastMonth = 3;// 用水与上月同期相比
				// int waterLastDays = 3;// 昨日用水情况
				dataMap.put("eleAll", eleAll);
				dataMap.put("eleLastYear", eleLastYear);
				dataMap.put("eleLastMonth", eleLastMonth);
				// dataMap.put("waterAll", waterAll);
				// dataMap.put("waterLastYear", waterLastYear);
				// dataMap.put("waterLastMonth", waterLastMonth);
				// dataMap.put("waterLastDays", waterLastDays);
			} else {
				Calendar cale = Calendar.getInstance();
				int month = cale.get(Calendar.MONTH);
				int day = cale.get(Calendar.DATE);
				cale.set(Calendar.DATE, 1);// 把日期设置为当月第一天
				cale.roll(Calendar.DATE, -1);// 日期回滚一天，也就是最后一天
				int maxDate = cale.get(Calendar.DATE);// 本月天数
				Properties config = StartUpClass.config;
				String[] degreePerMonth = config.getProperty("degreePerMonth")
						.split("\\|");
				int[] baseDegree = StringUtils.StringToInt(config.getProperty(
						"baseDegree").split("\\|"));
				int[] rewardDegree = StringUtils.StringToInt(config
						.getProperty("rewardDegree").split("\\|"));
				int eleAll = 0;// 年度总用电
				int eleThisMonth = deviceService.getEnergyThisMonth();// 本月用电
				int eleLastYear;// 用电与去年同期相比
				int eleLastMonth;// 用电与上月同期相比
				int waterAll = deviceService.getWaterAll();// 年度总用水

				Map<String, Integer> energyTrendThisYear = deviceService
						.getEnergyTrendDataThisYear();

				// 计算今年全年总用电。本月为止前无数据的月份用配置文件假数据替换
				if (!HandlerNullUtils.objectIsNull(energyTrendThisYear)) {
					int[] degreeThisYear = new int[12];
					for (int i = 0; i < energyTrendThisYear.size(); i++) {
						// BigDecimal 转 Integer
						Object object = energyTrendThisYear.get(String
								.valueOf(i + 1));
						degreeThisYear[i] = Integer.parseInt(String
								.valueOf(object));
						if (degreeThisYear[i] == 0 && i <= month) {
							degreeThisYear[i] = (baseDegree[i] + rewardDegree[i]) / 2;
						}
					}
					for (int i = 0; i < degreeThisYear.length; i++) {
						eleAll = eleAll + degreeThisYear[i];
					}
				}
				if (deviceService.getEnergyAllLastYear() != null) {
					float num = (float) (eleAll - deviceService
							.getEnergyAllLastYear())
							/ deviceService.getEnergyAllLastYear();
					DecimalFormat df = new DecimalFormat("0");// 格式化
					eleLastYear = Integer.parseInt(df.format(num * 100));
				} else {
					int eleLast = 0;
					for (int i = 0; i < month; i++) {
						eleLast = eleLast + Integer.parseInt(degreePerMonth[i]);
					}
					// 上年同期总用电
					eleLast = eleLast
							+ (Integer.parseInt(degreePerMonth[month]) / maxDate)
							* day;// 本月前总用电+(本月用电/本月天数)*当前天数
					float num = (float) (eleAll - eleLast) / eleLast;
					DecimalFormat df = new DecimalFormat("0");// 格式化
					eleLastYear = Integer.parseInt(df.format(num * 100));
				}
				if (deviceService.getEnergyLastMonth() != null) {
					float num = (float) (eleThisMonth - deviceService
							.getEnergyLastMonth())
							/ deviceService.getEnergyLastMonth();
					DecimalFormat df = new DecimalFormat("0");// 格式化
					eleLastMonth = Integer.parseInt(df.format(num * 100));
				} else {
					// 上月同期总用电
					int eleLast = (Integer.parseInt(degreePerMonth[month]) / maxDate)
							* day;// (本月用电/本月天数)*当前天数
					float num = (float) (eleThisMonth - eleLast) / eleLast;
					DecimalFormat df = new DecimalFormat("0");// 格式化
					eleLastMonth = Integer.parseInt(df.format(num * 100));
				}
				dataMap.put("eleAll", eleAll + " kW·h");
				dataMap.put("eleLastYear", eleLastYear);
				dataMap.put("eleLastMonth", eleLastMonth);
				dataMap.put("waterAll", waterAll + " m³");
			}
			messageBean.setType("success");
			messageBean.setMessage("故障趋势数据获取成功");
			messageBean.setData(dataMap);
		} catch (Exception e) {
			e.printStackTrace();
			messageBean.setType("fail");
			messageBean.setMessage("故障趋势数据获取失败");
		}
		return messageBean;
	}

	/**
	 * 能耗趋势
	 * 
	 * @return
	 */
	@RequestMapping("device/getEnergyTrendData")
	@ResponseBody
	public MessageBean getEnergyTrendData() {
		MessageBean messageBean = new MessageBean();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> energyTrendData = new HashMap<String, Object>();
		Properties config = StartUpClass.config;
		int[] baseDegree = StringUtils.StringToInt(config.getProperty(
				"baseDegree").split("\\|"));
		int[] rewardDegree = StringUtils.StringToInt(config.getProperty(
				"rewardDegree").split("\\|"));

		try {
			if ("test".equals(StartUpClass.EnergyTrendData)) {
				int[] degreeThisYear = { 99800, 129000, 138700, 146000, 178900,
						169000, 196600, 237800, 246000, 233600, 181300, 154400 };
				int[] degreeLastYear = { 116500, 87800, 145000, 130000, 167000,
						187000, 201000, 233400, 259000, 217000, 187000, 149000 };
				energyTrendData.put("degreeThisYear", degreeThisYear);
				energyTrendData.put("degreeLastYear", degreeLastYear);
			} else {
				Map<String, Integer> energyTrendThisYear = deviceService
						.getEnergyTrendDataThisYear();
				Map<String, Integer> energyTrendLastYear = deviceService
						.getEnergyTrendDataLastYear();
				Calendar cal = Calendar.getInstance();
				int month = cal.get(Calendar.MONTH) + 1;
				if (!HandlerNullUtils.objectIsNull(energyTrendThisYear)) {
					int[] degreeThisYear = new int[12];
					for (int i = 1; i <= energyTrendThisYear.size(); i++) {
						// BigDecimal 转 Integer
						Object object = energyTrendThisYear.get(String
								.valueOf(i));
						degreeThisYear[i - 1] = Integer.parseInt(String
								.valueOf(object));
						if (degreeThisYear[i - 1] == 0 && i < month) {
							degreeThisYear[i - 1] = (baseDegree[i - 1] + rewardDegree[i - 1]) / 2;
						}
					}
					energyTrendData.put("degreeThisYear", degreeThisYear);
				}
				if (!HandlerNullUtils.objectIsNull(energyTrendLastYear)) {
					int[] degreeLastYear = new int[12];
					for (int i = 1; i <= energyTrendLastYear.size(); i++) {
						// BigDecimal 转 Integer
						Object object = energyTrendLastYear.get(String
								.valueOf(i));
						degreeLastYear[i - 1] = Integer.parseInt(String
								.valueOf(object));
					}
					energyTrendData.put("degreeLastYear", degreeLastYear);
				} else {
					int[] degreeLastYear = { 99063, 80487, 91157, 94232,
							147691, 191205, 325313, 305803, 225943, 146361,
							129890, 85900 };
					energyTrendData.put("degreeLastYear", degreeLastYear);
				}
			}

			energyTrendData.put("baseDegree", baseDegree);
			energyTrendData.put("rewardDegree", rewardDegree);
			dataMap.put("energyTrendData", energyTrendData);
			messageBean.setType("success");
			messageBean.setMessage("故障趋势数据获取成功");
			messageBean.setData(dataMap);
		} catch (Exception e) {
			e.printStackTrace();
			messageBean.setType("fail");
			messageBean.setMessage("故障趋势数据获取失败");
		}
		return messageBean;
	}

	public List<Integer> getNumList(Map<String, Integer> map) {
		List<Integer> numList = new ArrayList<Integer>();
		numList.add(Integer.parseInt(map.get("1") + ""));
		numList.add(Integer.parseInt(map.get("2") + ""));
		numList.add(Integer.parseInt(map.get("3") + ""));
		numList.add(Integer.parseInt(map.get("4") + ""));
		numList.add(Integer.parseInt(map.get("5") + ""));
		numList.add(Integer.parseInt(map.get("6") + ""));
		numList.add(Integer.parseInt(map.get("7") + ""));
		numList.add(Integer.parseInt(map.get("8") + ""));
		numList.add(Integer.parseInt(map.get("9") + ""));
		numList.add(Integer.parseInt(map.get("10") + ""));
		numList.add(Integer.parseInt(map.get("11") + ""));
		numList.add(Integer.parseInt(map.get("12") + ""));
		return numList;
	}
}
